import { useState, useEffect } from 'react';

/** 网络状态类型 */
export interface INetworkType {
    /** 网络是否在线 */
    online: boolean;
    /** 当前连接下评估的往返时延 */
    rtt: number;
    /** 有效带宽估算（单位：兆比特/秒） */
    downlink: number;
    /** 网络连接的类型  */
    effectiveType: 'slow-2g' | '2g' | '3g' | '4g';
    /** 用户代理是否设置了减少数据使用的选项 */
    saveData: boolean;
}

/** 监听网络变化hooks */
export const useNetwork = () => {
    /** 当前网络状态 */
    const [networkInfo, setNetworkInfo] = useState<INetworkType | undefined>((() => {
        const { onLine, connection } = window.navigator as any;
        return {
            online: onLine,
            rtt: connection.rtt,
            downlink: connection.downlink,
            effectiveType: connection.effectiveType,
            saveData: connection.saveData
        }
    })());
    useEffect(() => {
        /** 设置当前网络状态 */
        const setCurrNetwork = () => {
            const { onLine, connection } = window.navigator as any;
            setNetworkInfo({
                online: onLine,
                rtt: connection.rtt,
                downlink: connection.downlink,
                effectiveType: connection.effectiveType,
                saveData: connection.saveData
            })
        }
        /** 开始监听 */
        window.addEventListener('online', setCurrNetwork, false);
        window.addEventListener('offline', setCurrNetwork, false);
        window.addEventListener('change', setCurrNetwork, false)

        /** 清除监听 */
        return () => {
            window.removeEventListener('online', setCurrNetwork, false);
            window.removeEventListener('offline', setCurrNetwork, false);
            window.removeEventListener('change', setCurrNetwork, false)
        }
    }, [])
    return networkInfo;
}
